// order.js
const app = getApp()

Page({
  data: {
    orders: [],           // 显示在页面上的订单列表
    allOrders: [],        // 从API获取的所有订单数据（用于筛选）
    currentTab: 0,
    tabs: [
      { id: 0, name: '全部' },
      { id: 1, name: '待付款' },
      { id: 2, name: '已支付' },
      { id: 3, name: '已取消' }
    ],
    loading: false,
    userInfo: {
      isLogin: false
    }
  },

  onLoad() {
    this.loadUserInfo()
    this.loadOrders()
  },

  onShow() {
    this.loadOrders()
  },

  // 加载用户信息
  loadUserInfo() {
    const globalUserInfo = app.getUserInfo()
    this.setData({ userInfo: globalUserInfo })
  },

  // 加载订单数据
  loadOrders() {
    if (!this.data.userInfo.isLogin) {
      this.setData({ 
        orders: [],
        allOrders: []
      })
      return
    }

    this.setData({ loading: true })
    this.getOrdersFromAPI()
  },

  // 从API获取订单数据
  getOrdersFromAPI() {
    console.log('开始获取订单数据，用户信息:', this.data.userInfo)
    
    // 获取用户ID
    const userId = this.data.userInfo.userId || this.data.userInfo.id
    if (!userId) {
      console.error('用户ID不存在')
      this.setData({ 
        loading: false,
        allOrders: [],
        orders: []
      })
      return
    }
    
    wx.request({
      url: `http://localhost:8081/product/OrderByUserId?userId=${userId}`,
      method: 'GET',
      success: (res) => {
        console.log('订单API响应:', res)
        this.setData({ loading: false })
        
        if (res.statusCode === 200 && res.data) {
          const orders = (Array.isArray(res.data) ? res.data : []).map(order => ({
            id: order.id,
            orderNo: order.orderNo,
            productId: order.productid,
            userId: order.userId,
            totalAmount: order.totalAmount,
            payAmount: order.payAmount,
            discountAmount: order.discountAmount,
            payType: order.payType,
            status: order.status,
            statusText: this.getStatusText(order.status),
            payTime: order.payTime,
            createTime: order.createTime,
            updateTime: order.updateTime,
            product: order.product || {},
            itemCount: 1 // 每个订单包含一个商品
          }))
          
          console.log('处理后的订单数据:', orders)
          
          this.setData({
            allOrders: orders,  // 保存所有订单数据
            orders: orders      // 默认显示所有订单
          })
          
          // 初始筛选
          this.filterOrders(this.data.currentTab)
        } else {
          console.log('API返回错误:', res.data)
          // 显示空状态
          this.setData({ 
            loading: false,
            allOrders: [],
            orders: []
          })
        }
      },
      fail: (err) => {
        console.error('获取订单数据失败:', err)
        // 显示空状态
        this.setData({ 
          loading: false,
          allOrders: [],
          orders: []
        })
      }
    })
  },


  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      'pending': '待付款',
      'paid': '已支付',
      'cancelled': '已取消',
      'shipped': '已发货',
      'delivered': '已送达',
      'refunded': '已退款'
    }
    return statusMap[status] || '未知状态'
  },

  // 切换标签
  onTabChange(e) {
    const tabId = e.currentTarget.dataset.id
    this.setData({ currentTab: tabId })
    this.filterOrders(tabId)
  },

  // 筛选订单
  filterOrders(tabId) {
    let filteredOrders = []
    
    switch(tabId) {
      case 0: // 全部
        filteredOrders = this.data.allOrders
        break
      case 1: // 待付款
        filteredOrders = this.data.allOrders.filter(order => order.status === 'pending')
        break
      case 2: // 已支付
        filteredOrders = this.data.allOrders.filter(order => 
          order.status === 'paid' || order.status === 'shipped' || order.status === 'delivered'
        )
        break
      case 3: // 已取消
        filteredOrders = this.data.allOrders.filter(order => 
          order.status === 'cancelled' || order.status === 'refunded'
        )
        break
    }
    
    this.setData({ orders: filteredOrders })
  },

  // 订单项点击
  onOrderTap(e) {
    const order = e.currentTarget.dataset.order
    if (!order) return
    
    wx.navigateTo({
      url: `/pages/order-detail/order-detail?id=${order.id}`
    })
  },

  // 支付订单
  onPayOrder(e) {
    const order = e.currentTarget.dataset.order
    if (!order) return
    
    // 跳转到订单详情页面进行支付
    wx.navigateTo({
      url: `/pages/order-detail/order-detail?id=${order.id}`,
      fail: (err) => {
        console.error('跳转订单详情失败:', err)
        wx.showToast({
          title: '跳转失败',
          icon: 'none'
        })
      }
    })
  },

  // 取消订单
  onCancelOrder(e) {
    const order = e.currentTarget.dataset.order
    if (!order) return
    
    // 检查订单状态，只有待付款的订单才能取消
    if (order.status !== 'pending') {
      wx.showToast({
        title: '只有待付款订单才能取消',
        icon: 'none'
      })
      return
    }
    
    wx.showModal({
      title: '确认取消',
      content: `确定要取消订单 ${order.orderNo} 吗？\n取消后将无法恢复。`,
      confirmText: '确认取消',
      cancelText: '再想想',
      success: (res) => {
        if (res.confirm) {
          this.cancelOrderAPI(order.id, order)
        }
      }
    })
  },

  // 调用取消订单API
  cancelOrderAPI(orderId, order) {
    console.log('开始取消订单，订单ID:', orderId)
    
    wx.showLoading({
      title: '正在取消订单...'
    })
    
    wx.request({
      url: `http://localhost:8081/product/OrderQuxiao?id=${orderId}`,
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      success: (res) => {
        wx.hideLoading()
        console.log('取消订单API响应:', res.data)
        
        if (res.statusCode === 200 && res.data) {
          // 取消成功，更新订单状态
          const allOrders = this.data.allOrders.map(item => {
            if (item.id === orderId) {
              return { ...item, status: 'cancelled', statusText: '已取消' }
            }
            return item
          })
          
          this.setData({ allOrders })
          this.filterOrders(this.data.currentTab)
          
          wx.showToast({
            title: '订单取消成功',
            icon: 'success'
          })
        } else {
          console.error('取消订单失败:', res.data)
          wx.showModal({
            title: '取消订单失败',
            content: res.data.message || res.data.error || '请稍后重试',
            showCancel: false,
            confirmText: '确定'
          })
        }
      },
      fail: (err) => {
        wx.hideLoading()
        console.error('取消订单失败:', err)
        wx.showModal({
          title: '网络错误',
          content: '取消订单失败，请检查网络连接后重试',
          showCancel: false,
          confirmText: '确定'
        })
      }
    })
  },


  // 去登录
  goToLogin() {
    wx.navigateTo({
      url: '/pages/login/login'
    })
  },

  // 去商城
  goToShop() {
    wx.switchTab({
      url: '/pages/mall/mall'
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadOrders()
    wx.stopPullDownRefresh()
  }
})